<template>
  <view class="password-container">
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        <text>返回</text>
      </view>
      <view class="header-title">修改交易密码</view>
      <view class="header-right"></view>
    </view>
    
    <view class="content">
      <view class="step-indicator">
        <view class="step" :class="{active: currentStep >= 1}">
          <view class="step-number">1</view>
          <text class="step-text">验证身份</text>
        </view>
        <view class="step-line" :class="{active: currentStep >= 2}"></view>
        <view class="step" :class="{active: currentStep >= 2}">
          <view class="step-number">2</view>
          <text class="step-text">设置密码</text>
        </view>
        <view class="step-line" :class="{active: currentStep >= 3}"></view>
        <view class="step" :class="{active: currentStep >= 3}">
          <view class="step-number">3</view>
          <text class="step-text">完成</text>
        </view>
      </view>
      
      <!-- 步骤1：验证身份 -->
      <view v-if="currentStep === 1" class="step-content">
        <view class="form-section">
          <view class="form-item">
            <view class="form-label">姓名</view>
            <view class="form-input-group">
              <input class="form-input" v-model="formData.username" placeholder="请输入姓名" />
            </view>
          </view>
          
          <view class="form-item">
            <view class="form-label">身份证号</view>
            <view class="form-input-group">
              <input class="form-input" v-model="formData.idCard" placeholder="请输入身份证号" maxlength="18" />
            </view>
          </view>
          
          <!-- <view class="form-item">
            <view class="form-label">当前交易密码</view>
            <view class="form-input-group">
              <input class="form-input" v-model="formData.pastPassword" placeholder="请输入当前6位交易密码" type="password" maxlength="6" inputmode="numeric" pattern="[0-9]*" />
            </view>
          </view> -->
        </view>
        
        <button class="action-btn" @click="verifyIdentity">下一步</button>
      </view>
      
      <!-- 步骤2：设置密码 -->
      <view v-if="currentStep === 2" class="step-content">
        <view class="form-section">
          <view class="form-item">
            <view class="form-label">旧密码</view>
            <view class="form-input-group">
              <input 
                class="form-input" 
                v-model="formData.pastPassword" 
                placeholder="请输入旧密码" 
                :type="showPastPassword ? 'text' : 'password'" 
                maxlength="6" 
                inputmode="numeric" 
                pattern="[0-9]*"
              />
              <view class="eye-icon" @click="togglePastPasswordVisibility">
                <u-icon :name="showPastPassword ? 'eye' : 'eye-off'" size="24" color="#999"></u-icon>
              </view>
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">交易密码</view>
            <view class="form-input-group">
              <input 
                class="form-input" 
                v-model="formData.password" 
                placeholder="请输入6位数字交易密码" 
                :type="showPassword ? 'text' : 'password'" 
                maxlength="6" 
                inputmode="numeric" 
                pattern="[0-9]*"
              />
              <view class="eye-icon" @click="togglePasswordVisibility">
                <u-icon :name="showPassword ? 'eye' : 'eye-off'" size="24" color="#999"></u-icon>
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <view class="form-label">确认密码</view>
            <view class="form-input-group">
              <input 
                class="form-input" 
                v-model="formData.confirmPassword" 
                placeholder="请再次输入交易密码" 
                :type="showConfirmPassword ? 'text' : 'password'" 
                maxlength="6" 
                inputmode="numeric" 
                pattern="[0-9]*"
              />
              <view class="eye-icon" @click="toggleConfirmPasswordVisibility">
                <u-icon :name="showConfirmPassword ? 'eye' : 'eye-off'" size="24" color="#999"></u-icon>
              </view>
            </view>
          </view>
          
          <view class="password-tips">
            <u-icon name="info-circle" size="16" color="#999"></u-icon>
            <text class="tip-text">交易密码用于资金相关操作，请勿与登录密码相同</text>
          </view>
        </view>
        
        <button class="action-btn" @click="setPassword">确认修改</button>
      </view>
      
      <!-- 步骤3：完成 -->
      <view v-if="currentStep === 3" class="step-content">
        <view class="success-section">
          <view class="success-icon">
            <u-icon name="checkmark-circle" size="80" color="#07c160"></u-icon>
          </view>
          <view class="success-title">交易密码修改成功</view>
          <view class="success-desc">您的交易密码已成功修改，请妥善保管</view>
        </view>
        
        <button class="action-btn" @click="goBack">完成</button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { updateUserPassword } from '@/api/user'

export default {
  data() {
    return {
      currentStep: 1,
      showPassword: false,
      showPastPassword: false,
      showConfirmPassword: false,
      formData: {
        username: '',
        idCard: '',
        pastPassword: '',
        password: '',
        confirmPassword: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  onLoad() {
    // 预填充用户名和身份证号
    if (this.userInfo && this.userInfo.id) {
      this.formData.username = this.userInfo.username || '';
      this.formData.idCard = this.userInfo.idCard || '';
    }
  },
  methods: {
    ...mapActions(['GetUserInfo']),
    
    goBack() {
      if (this.currentStep === 3) {
        uni.navigateBack({
          delta: 1
        });
      } else {
        uni.showModal({
          title: '提示',
          content: '确定要放弃修改交易密码吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack();
            }
          }
        });
      }
    },
    checkIdNumber(idNumber) {
        // 正则表达式验证身份证格式
        const reg = /^(?:\d{15}|\d{17}[\dX])$/;
        if (!reg.test(idNumber)) {
            console.error('身份证号码格式不正确');
            return false;
        }

        // 如果是18位身份证，进行校验位验证
        if (idNumber.length === 18) {
            const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            const checkDigits = '10X98765432';
            let sum = 0;

            for (let i = 0; i < 17; i++) {
                sum += idNumber[i] * weights[i];
            }

            const checkDigit = checkDigits[sum % 11];
            if (checkDigit !== idNumber[17]) {
                console.error('身份证号码校验位不正确');
                return false;
            }
        }

        console.log('身份证号码有效');
        return true;
    },
    verifyIdentity() {
      if (!this.formData.username) {
        return uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        });
      }
      
      if (!this.formData.idCard || !this.checkIdNumber(this.formData.idCard)) {
        return uni.showToast({
          title: '请输入正确的身份证号',
          icon: 'none'
        });
      }
      
      // if (!this.formData.pastPassword) {
      //   return uni.showToast({
      //     title: '请输入当前密码',
      //     icon: 'none'
      //   });
      // }
      
      // 验证成功，进入下一步
      this.currentStep = 2;
    },
    
    setPassword() {
      if (!this.formData.pastPassword) {
        return uni.showToast({
          title: '请输入旧密码',
          icon: 'none'
        });
      }
      

      if (!this.formData.password) {
        return uni.showToast({
          title: '请输入新密码',
          icon: 'none'
        });
      }
      
      if (this.formData.password.length < 6) {
        return uni.showToast({
          title: '密码长度不能少于6位',
          icon: 'none'
        });
      }
      
      if (!this.formData.confirmPassword) {
        return uni.showToast({
          title: '请确认新密码',
          icon: 'none'
        });
      }
      
      if (this.formData.password !== this.formData.confirmPassword) {
        return uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        });
      }
      
      // 如果新密码和旧密码相同
      if (this.formData.password === this.formData.pastPassword) {
        return uni.showToast({
          title: '新密码不能与旧密码相同',
          icon: 'none'
        });
      }
      
      // 提交修改密码
      this.submitPasswordUpdate();
    },
    
    // 提交密码修改
    submitPasswordUpdate() {
      if (this.loading) return;
      
      this.loading = true;
      uni.showLoading({
        title: '提交中...'
      });
      
      // 构建请求参数
      const params = {
        username: this.formData.username,
        idCard: this.formData.idCard,
        password: this.formData.password,
        pastPassword: this.formData.pastPassword
      };
      
      // 调用修改密码接口
      updateUserPassword(params).then(res => {
        this.loading = false;
        uni.hideLoading();
        
        if (res.data && res.data.code === 0) {
          // 修改成功
          this.currentStep = 3;
        } else {
          // 修改失败
          uni.showModal({
            title: '修改失败',
            content: res.data.msg || '密码修改失败，请稍后重试',
            showCancel: false
          });
        }
      }).catch(error => {
        console.log(error);
        this.loading = false;
        uni.hideLoading();
        uni.showModal({
          title: '修改失败',
          content: error.message || '网络异常，请稍后重试',
          showCancel: false
        });
      });
    },
    
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    togglePastPasswordVisibility() {
      this.showPastPassword = !this.showPastPassword;
    },
    toggleConfirmPasswordVisibility() {
      this.showConfirmPassword = !this.showConfirmPassword;
    }
  }
}
</script>

<style lang="scss">
.password-container {
  min-height: 100vh;
  background-color: #f7f7f7;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  width: 60rpx;
}

.content {
  padding: 30rpx;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 50rpx;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-number {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: #ddd;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  margin-bottom: 10rpx;
}

.step.active .step-number {
  background-color: #1989fa;
}

.step-text {
  font-size: 24rpx;
  color: #999;
}

.step.active .step-text {
  color: #1989fa;
}

.step-line {
  width: 100rpx;
  height: 2rpx;
  background-color: #ddd;
  margin: 0 15rpx;
  margin-bottom: 30rpx;
}

.step-line.active {
  background-color: #1989fa;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.form-input-group {
  display: flex;
  align-items: center;
}

.form-input {
  flex: 1;
  height: 80rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}

.verify-code-btn {
  width: 200rpx;
  height: 80rpx;
  background-color: #1989fa;
  color: #fff;
  font-size: 26rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
}

.verify-code-btn.disabled {
  background-color: #ccc;
}

.password-tips {
  display: flex;
  align-items: flex-start;
  margin-top: 20rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
  flex: 1;
}

.action-btn {
  height: 90rpx;
  background-color: #1989fa;
  color: #fff;
  font-size: 30rpx;
  font-weight: 500;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 50rpx 0 30rpx;
}

.success-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 50rpx 0;
}

.success-icon {
  margin-bottom: 30rpx;
}

.success-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.success-desc {
  font-size: 28rpx;
  color: #999;
}

.eye-icon {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10rpx;
}
</style> 